/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.momarketing.service;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boxin.framework.base.utils.Constants;
import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.dao.CouponDao;
import com.boxin.ims.modules.momarketing.dao.QRCodeDao;
import com.boxin.ims.modules.momarketing.entity.Coupon;
import com.boxin.ims.modules.momarketing.entity.CouponConfig;
import com.boxin.ims.modules.momarketing.entity.QRCode;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.UserDefineService;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.thinkgem.jeesite.common.persistence.BaseEntity;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.FileUtils;

/**
 * 优惠券Service
 * @author Jakemanse
 * @version 2013-05-25
 */
@Component
@Transactional(readOnly = true)
public class CouponService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(CouponService.class);
	
	@Autowired
	private CouponDao couponDao;
	
	
	@Autowired
	private QRCodeDao QRCodeDao;
	
	
	@Autowired
	CouponConfigService  couponConfigService;
	
	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	private UserDefineService userDefineService;
	
	public Coupon get(Long id) {
		return couponDao.findOne(id);
	}
	
	
	public Coupon getByNumber(String number){
		DetachedCriteria dc = couponDao.createDetachedCriteria();
		if(number != null){
			dc.add(Restrictions.eq("number", number));
		}
		
		List<Coupon> couponList = couponDao.find(dc);
		if(couponList != null ){
			if(!couponList.isEmpty())
				return couponList.get(0);
		}
		
		return null;
		
	}
	
	public Page<Coupon> find(Page<Coupon> page, Coupon coupon) {
		DetachedCriteria dc = couponDao.createDetachedCriteria();
		if(coupon.getUser()!=null && coupon.getUser().getId()!=null){
			if(!coupon.getUser().isAdmin()){
				dc.add(Restrictions.eq("user.id", coupon.getUser().getId()));
			}
		}
		if (StringUtils.isNotEmpty(coupon.getName())){
			dc.add(Restrictions.like("name", "%"+coupon.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(coupon.getNumber())){
			dc.add(Restrictions.like("number", "%"+coupon.getNumber()+"%"));
		}
		if (StringUtils.isNotEmpty(coupon.getMobile())){
			dc.add(Restrictions.like("mobile", "%"+coupon.getMobile()+"%"));
		}
		if(coupon.getCreateTime() !=null){
			String timeField = "createTime";
			if (StringUtils.isNotEmpty(coupon.getStatus()) && BaseEntity.STATUS_CLEAR.equals(coupon.getStatus())){
				timeField = "updateTime";
			}
			dc.add(Restrictions.ge(timeField,coupon.getCreateTime() ));
		}
		
		if(coupon.getEndTime() !=null){
			String timeField = "createTime";
			if (StringUtils.isNotEmpty(coupon.getStatus()) && BaseEntity.STATUS_CLEAR.equals(coupon.getStatus())){
				timeField = "updateTime";
			}
			dc.add(Restrictions.le(timeField,coupon.getEndTime()));
		}
		if (StringUtils.isNotEmpty(coupon.getStatus())){
			dc.add(Restrictions.eq("status",  coupon.getStatus() ));
		}
		if (StringUtils.isNotEmpty(coupon.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+coupon.getRemarks()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", Coupon.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return couponDao.find(page, dc);
	}
	
	
	public List<Coupon> find(Coupon coupon) {
		DetachedCriteria dc = couponDao.createDetachedCriteria();
		if(coupon.getUser()!=null && coupon.getUser().getId()!=null){
			if(!coupon.getUser().isAdmin()){
				dc.add(Restrictions.eq("user.id", coupon.getUser().getId()));
			}
		}
		if (StringUtils.isNotEmpty(coupon.getName())){
			dc.add(Restrictions.like("name", "%"+coupon.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(coupon.getNumber())){
			dc.add(Restrictions.like("number", "%"+coupon.getNumber()+"%"));
		}
		if (StringUtils.isNotEmpty(coupon.getMobile())){
			dc.add(Restrictions.like("mobile", "%"+coupon.getMobile()+"%"));
		}
		if(coupon.getCreateTime() !=null){
			String timeField = "createTime";
			if (StringUtils.isNotEmpty(coupon.getStatus()) && BaseEntity.STATUS_CLEAR.equals(coupon.getStatus())){
				timeField = "updateTime";
			}
			dc.add(Restrictions.ge(timeField,coupon.getCreateTime() ));
		}
		
		if(coupon.getEndTime() !=null){
			String timeField = "createTime";
			if (StringUtils.isNotEmpty(coupon.getStatus()) && BaseEntity.STATUS_CLEAR.equals(coupon.getStatus())){
				timeField = "updateTime";
			}
			dc.add(Restrictions.le(timeField,coupon.getEndTime()));
		}
		if (StringUtils.isNotEmpty(coupon.getStatus())){
			dc.add(Restrictions.eq("status",  coupon.getStatus() ));
		}
		if (StringUtils.isNotEmpty(coupon.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+coupon.getRemarks()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", Coupon.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return couponDao.find( dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Coupon coupon) {
		
		
//		// 生成二维码
//		QRCode qrCode = new QRCode();
//		
//		String qrPath = Constants.getEcardQRCodeResourceSavePath();
//		qrCode.setContent(QRCodeUtils.generateCouponSN(coupon.getUser().getId()));
//		qrCode.setJpegPath(qrPath +qrCode.getContent());
//		//生成二维码
//		QRCodeUtils.generateQRCodeJPEG(qrCode.getContent(),
//				qrCode.getJpegPath(), 150, 150);
//		
//		QRCode savedqrCode = QRCodeDao.save(qrCode);
//		
		/**
		 * 
		 */
		
		int width = QRCodeUtils.WIDTH;
		int height =QRCodeUtils.HEIGHT;
//		UserDefine userDefine  = userDefineService.getByUserId(coupon.getUser().getId());
//		if(userDefine!=null){
//			if(userDefine.getQrcodeHeight()!=null){
//				height = userDefine.getQrcodeHeight();
//			}
//			if(userDefine.getQrcodeWidth()!=null){
//				width = userDefine.getQrcodeWidth();
//			}
//		}
		//生成二维码
		QRCode qrcode = new QRCode();
		String content = QRCodeUtils.generateCouponSN(coupon.getUser().getId());
		qrcode.setContent(content);
		String path = Constants.getWechatResourceSavePath();
		path += DateUtils.getTodayString()+File.separator+content;
		FileUtils.createDirectory(path);
		QRCodeUtils.generateQRCodePNG(content, path, width,height);
		qrcode.setFileName(content+".png");
		qrcode.setPngPath(path+".png");
		QRCodeDao.save(qrcode);	//保存二维码	
		
		coupon.setNumber(qrcode.getContent());
		coupon.setQrCode(qrcode);
		
		couponDao.save(coupon);
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		couponDao.deleteById(id);
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-10  下午4:14:30
	 * @function <p> 优惠券核销 </p>
	 * @param id
	 */
	@Transactional(readOnly = false)
	public void cancel(Long id) {
		Coupon coupon = get(id);
		CouponConfig config =	couponConfigService.get(coupon.getConfig().getId()) ;
		if(config != null){
			if(Coupon.SOURCE_TYPE_WP.equals(config.getUsingType()) && config.getMemberScore() > 0){	//如果是微信优惠券，则积分计算
				WechatMember wechatMember = wechatMemberService.getByWechatMemberId(coupon.getUser(), coupon.getSourceId());
				wechatMember.setScore(wechatMember.getScore() + config.getMemberScore());
				ScoreUtils.addWechatMemberCouponScore(wechatMember, coupon, config.getMemberScore());
			}
		}
		//核销 
		coupon.setStatus(Coupon.CANCEL_FLAG_DELETE);
		save(coupon);
	}
	
}
